package com.chb.test;

import com.chb.utils.ESClient;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.Test;

import java.io.IOException;
import java.util.Map;

public class IDQueryDemo {
    RestHighLevelClient client = ESClient.getClient();
    //定义索引名
    String index = "sms-logs-index";

    @Test
    public void idQuery() throws IOException {
        GetRequest request = new GetRequest(index);

        GetResponse resp = client.get(request.id("1"), RequestOptions.DEFAULT);

        System.out.println(resp);
    }

    @Test
    public void idsQuery() throws IOException {
        //1。创建request对象，查询用的对象一般都是SearchRequest对象
        SearchRequest mySearchRequest = new SearchRequest(index);

        //2，指定查询条件，依赖查询条件的对象SearchSourceBuilder的对象
        SearchSourceBuilder builder = new SearchSourceBuilder();
        builder.from(0).size(10).query(QueryBuilders.idsQuery().addIds("1", "2", "3"));

        mySearchRequest.source(builder);
        //3. 执行查询
        SearchResponse search = client.search(mySearchRequest, RequestOptions.DEFAULT);

        //4. 获取到_source中的数据，并展示
        //注意RESTFUL风格上是两个hits，所以这里要两次getHits()
        for (SearchHit hit : search.getHits().getHits()) {
            Map<String, Object> result = hit.getSourceAsMap();
            System.out.println(result);
        }
    }


}
